package com.bblocks.standard.utils;

import cn.hutool.http.HttpUtil;

import java.io.IOException;
import java.nio.charset.Charset;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * HttpServletResponse帮助类
 */
public class ResponseUtils {

	public static void renderJson(HttpServletResponse response, String text) {
		// System.out.print(text);
		render(response, "text/plain;charset=UTF-8", text);
	}

	/**
	 * 发送内容。使用UTF-8编码。
	 *
	 * @param response
	 * @param contentType
	 * @param text
	 */
	public static void render(HttpServletResponse response, String contentType, String text) {
		response.setContentType(contentType);
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void render(HttpServletResponse response, String contentType, byte[] bytes) {
		response.reset();
		response.setContentType(contentType);
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try(ServletOutputStream stream = response.getOutputStream()) {
			stream.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static final String TARGET = "https://www.mca.gov.cn/mzsj/xzqh/2022/202201xzqh.html";
	public static void main(String[] args) {
		String areas = HttpUtil.downloadString(TARGET, Charset.forName("utf-8"));
		System.out.println(areas);
	}
}